package org.test.once.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.test.once.manager.LoginManager;
import org.test.once.manager.UserManager;
import org.test.once.model.Module;
import org.test.once.model.User;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("gb2312");
		
		UserManager userManager = new UserManager();
		String command = request.getParameter("command");
		System.out.println("command=" + command);
		if ("login".equals(command)) {
			String account = request.getParameter("account");
			String password = request.getParameter("password");
			System.out.println("account=" + account + " password=" + password);
			User user = userManager.login(account, password);
			if (user != null) {
				// 将用户添加到session中
				request.getSession().setAttribute("login", user);
				List<Module> modules = new LoginManager().getModules(user.getRoleId());
//				request.setAttribute("modules", modules);
				request.getSession().setAttribute("modules", modules);
				
				request.getRequestDispatcher("maint.jsp").forward(request, response);
			} else {
				response.sendRedirect("index.jsp");
			}
		} else if("menu".equals(command)) {
			System.out.println("----------------menu-------------");
			List<Module> modules = (List<Module>)request.getSession().getAttribute("modules");
			request.setAttribute("modules", modules);
			request.getSession().removeAttribute("modules");
			for (Iterator iterator = modules.iterator(); iterator.hasNext();) {
				Module module = (Module) iterator.next();
				System.out.println(module.getName());
			}
			request.getRequestDispatcher("menu.jsp").forward(request, response);
		} else {
			response.sendRedirect("index.jsp");
		}
	}

}
